package cn.deali.homework9.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import cn.deali.homework9.R;
import cn.deali.homework9.adapter.TopMusicListAdapter;
import cn.deali.homework9.model.OnlineMusic;
import cn.deali.homework9.model.TopMusicList;
import cn.deali.homework9.utils.OnlineMusicUtils;

public class TopMusicListFragment extends Fragment {
    Context context;
    View view;

    @SuppressWarnings("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what != 1) {
                Toast.makeText(context, "获取网易云音乐失败", Toast.LENGTH_SHORT).show();
                return;
            }

            List<TopMusicList> topMusicLists = (List<TopMusicList>) msg.obj;

            RecyclerView recyclerView = view.findViewById(R.id.onlineMusicList);
            TopMusicListAdapter adapter = new TopMusicListAdapter(context, topMusicLists);
            recyclerView.setAdapter(adapter);

            //设置layout manager，默认垂直分布
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            recyclerView.setLayoutManager(linearLayoutManager);
        }
    };

    public TopMusicListFragment(Context context) {
        this.context = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_online_music, container, false);

        new GetTopMusicListsThread().start();

        return view;
    }


    class GetTopMusicListsThread extends Thread {
        @Override
        public void run() {
            super.run();
            List<TopMusicList> topMusicLists = OnlineMusicUtils.getTopMusicList(context);

            Message message = new Message();
            if (topMusicLists.size() > 0)
                message.what = 1;
            else
                message.what = 0;
            message.obj = topMusicLists;
            handler.sendMessage(message);
        }
    }
}
